<?php

namespace App\Trip\Orders\BookOrders\Params\AbstractOrderParam;

use App\Trip\Orders\TransferFlag;

abstract class AbstractMultiTripOrders
{
    protected string $trip_id;
    protected array  $orders_data;

    public abstract function getOrders(): array;

    public function dealOrders(array $ordersData, string $orderParamClass): array
    {
        // 去除意外的键值
        $ordersData  = collect($ordersData)->values();
        $order_count = count($ordersData);
        return collect($ordersData)
            ->map(function ($order, $index) use ($order_count, $orderParamClass) {
                $trip_no = $index + 1;
                // 校对 trip no
                if (!isset($order['trip_no'])) {
                    $order['trip_no'] = $trip_no;
                }

                if ($order['trip_no'] != $trip_no) {
                    $order['trip_no'] = $trip_no;
                }
                // 如果只有一个订单 标识无中转
                if ($order_count == 1) {
                    $order['transfer_flag'] = TransferFlag::ORDER_TRANSFER_FLAG_NONE;
                } else {
                    // 中转编号 = 行程编号
                    $order['transfer_flag'] = $order['trip_no'];
                }

                $order['trip_id'] = $this->getTripId();
                return new $orderParamClass($order);
            })
            // 根据时间排序 矫正行程序号
            ->sortBy('start_at')->toArray();
    }

    public function getTripId(): string
    {
        return $this->trip_id;
    }

    protected function setTripId(string $trip_id): void
    {
        $this->trip_id = $trip_id;
    }

    protected function setOrders(array $orders_data): void
    {
        $this->orders_data = $orders_data;
    }
}